package com.t4.courseware.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.t4.courseware.common.Result;
import com.t4.courseware.handler.UserThreadLocal;
import com.t4.courseware.mapper.CoursewareMapper;
import com.t4.courseware.mapper.OrderMapper;
import com.t4.courseware.mapper.UserCoursewareMapper;
import com.t4.courseware.pojo.Courseware;
import com.t4.courseware.pojo.Order;
import com.t4.courseware.pojo.UserCourseware;
import com.t4.courseware.pojo.dto.UserDto;
import com.t4.courseware.service.OrderService;
import com.yungouos.pay.util.PaySignUtil;
import com.yungouos.pay.wxpay.WxPay;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.UUID;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Resource
    private UserCoursewareMapper userCoursewareMapper;
    @Resource
    private CoursewareMapper coursewareMapper;
    @Resource
    private OrderMapper orderMapper;
    @Value("${wxpay.mchid}")
    private String mchid;
    @Value("${wxpay.key}")
    private String key;

    @Transactional
    public Result createOrder(Order order) {
        UserDto userDto = UserThreadLocal.get();
        BigDecimal price = order.getPrice();
        UserCourseware userCourseware = userCoursewareMapper.selectOne(Wrappers.<UserCourseware>lambdaQuery().eq(UserCourseware::getUserId, userDto.getId()).eq(UserCourseware::getCwId, order.getCwId()));

        Courseware courseware = coursewareMapper.selectOne(Wrappers.<Courseware>lambdaQuery().eq(Courseware::getUploadUserId, userDto.getId()).eq(Courseware::getId, order.getCwId()));
        if (userCourseware == null && courseware == null && price.compareTo(BigDecimal.ZERO) > 0) {
            order.setIsPay(false);
            order.setCreateTime(LocalDateTime.now());
            order.setPayTime(null);
            order.setId(null);
            Courseware courseware1 = coursewareMapper.selectById(order.getCwId());
            order.setOrderSn(UUID.randomUUID().toString());
            order.setPrice(courseware1.getPrice());
            order.setUserId(userDto.getId());
            orderMapper.insert(order);
            JSONObject jsonObject = WxPay.minAppPay(
                    order.getOrderSn(),
                    "" + order.getPrice(),
                    mchid,
                    "购买资料ID为:" + order.getCwId(),
                    "小谷文市",
                    null,
                    "http://www.t4dmw.top/cwApi/order/callback",
                    null,
                    "0",
                    null,
                    null,
                    null,
                    key);
            return Result.SUCCESS(jsonObject);
        } else if(price.compareTo(BigDecimal.ZERO) <= 0){
            Courseware courseware2 = coursewareMapper.selectById(order.getCwId());
            courseware2.setCount(courseware2.getCount()+1);
            coursewareMapper.updateById(courseware2);
            order.setIsPay(true);
            order.setPayTime(LocalDateTime.now());
            order.setPayType(0);
            UserCourseware userCourseware2 = new UserCourseware();
            userCourseware2.setCwId(order.getCwId());
            userCourseware2.setUserId(userDto.getId());
            userCoursewareMapper.insert(userCourseware2);
            orderMapper.updateById(order);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("message", "first");
            return Result.SUCCESS(jsonObject);
        } else {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("message", "second");
            return Result.SUCCESS(jsonObject);
        }
    }

    @Transactional
    public boolean callBack(JSONObject callback, HttpServletRequest request) {
        try {
            boolean b = PaySignUtil.checkNotifySign(request, key);
            if (b) {
                String wxOrder = (String) callback.get("orderNo");
                Order outTradeNo = orderMapper.selectOne(Wrappers.<Order>lambdaQuery().eq(Order::getOrderSn, callback.get("outTradeNo")));
                Courseware courseware = coursewareMapper.selectById(outTradeNo.getCwId());
                courseware.setCount(courseware.getCount()+1);
                coursewareMapper.updateById(courseware);
                outTradeNo.setIsPay(true);
                outTradeNo.setPayTime(LocalDateTime.now());
                outTradeNo.setPayType(0);
                outTradeNo.setWxOrder(wxOrder);
                UserCourseware userCourseware = new UserCourseware();
                userCourseware.setCwId(outTradeNo.getCwId());
                userCourseware.setUserId(outTradeNo.getUserId());
                userCoursewareMapper.insert(userCourseware);
                orderMapper.updateById(outTradeNo);
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


}
